package com.sl.core.engine.datasource;

import cn.hutool.core.collection.CollUtil;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.page.PageRequest;
import org.beetl.sql.core.page.PageResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SlSQLManager {

    public static <T> PageResult<T> executePageQuery(SQLManager sqlManager, String sqlTemplate, Class<T> clazz, Object paras,
                                                     PageRequest<T> request) {
//        SagaContext sagaContext = SagaContext.sagaContextFactory.current();

        Long count = null;
        List<T> list = null;
        if (request.isTotalRequired()) {
            String countSql = sqlManager.getSqlManagerExtend().getPageKit().getCountSql(sqlManager.getDbStyle().getName(), sqlTemplate);

            List<Long> countList = sqlManager.execute(countSql, Long.class, paras);
            count = CollUtil.get(countList, 0);
            if (count == null || count == 0 || !request.isListRequired()) {
                list = new ArrayList<>();
                return request.of(list, 0L);
            }
        }

        if (request.isListRequired()) {
            long pageSize = request.getPageSize();
            Object offset = request.getStart(sqlManager.isOffsetStartZero());
            String pageSql = sqlManager.getDbStyle().getRangeSql().toRange(sqlTemplate, offset, pageSize);
            list = sqlManager.execute(pageSql, clazz, paras);

        } else {
            list = Collections.EMPTY_LIST;
        }
        return request.isTotalRequired() ? request.of(list, count) : request.of(list);
    }

}
